/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.acceptance.util.worker;

import java.util.List;

import org.easymock.classextension.EasyMock;
import org.ourgrid.acceptance.util.WorkerAcceptanceUtil;
import org.ourgrid.common.interfaces.management.RemoteWorkerManagement;
import org.ourgrid.common.interfaces.management.WorkerManagement;
import org.ourgrid.common.interfaces.management.WorkerManagementClient;
import org.ourgrid.worker.WorkerComponent;

import br.edu.ufcg.lsd.commune.container.ContainerContext;
import br.edu.ufcg.lsd.commune.container.ObjectDeployment;
import br.edu.ufcg.lsd.commune.container.logging.CommuneLogger;
import br.edu.ufcg.lsd.commune.container.servicemanager.FileTransferManager;
import br.edu.ufcg.lsd.commune.identification.ContainerID;
import br.edu.ufcg.lsd.commune.identification.DeploymentID;
import br.edu.ufcg.lsd.commune.processor.filetransfer.IncomingTransferHandle;
import br.edu.ufcg.lsd.commune.processor.filetransfer.OutgoingTransferHandle;
import br.edu.ufcg.lsd.commune.processor.filetransfer.TransferHandle;
import br.edu.ufcg.lsd.commune.test.AcceptanceTestUtil;


public class Req_006_Util extends WorkerAcceptanceUtil {

	public Req_006_Util(ContainerContext context) {
		super(context);
	}

	public void workForPeerOnOwnerWorker(WorkerComponent component, String senderPubKey) {
		workForPeer(component, null, senderPubKey, null, true, true, true, false,
				false, false, false, null, null);
	}
	
	public void workForPeerByNotMasterPeer(WorkerComponent component, String senderPubKey) {
		workForPeer(component, null, senderPubKey, null, true, false, false, false,
				false, false, false, null, null);
	}
	
	public void workForPeerByUnknownPeer(WorkerComponent component, String senderPubKey) {
		workForPeer(component, null, senderPubKey, null, false, false, false, false,
				false, false, false, null, null);
	}

	public void workForPeerOnIdleWorker(WorkerComponent component, WorkerManagementClient wmc,
			String senderPubKey, String remotePeerPubKey) {
		workForPeer(component, wmc, senderPubKey, remotePeerPubKey, true, true, false,
				false, true, false, false, null, null);
	}
	
	public void workForPeerOnAllocatedForMyGridWorker(WorkerComponent component, WorkerManagementClient wmc,
			String senderPubKey, String remotePeerPubKey) {
		workForPeer(component, wmc, senderPubKey, remotePeerPubKey, true, true, false,
				true, false, true, false, null, null);
	}
	
	public void workForPeerOnAllocatedForMyGridWorkerWithCleaningError(WorkerComponent component, WorkerManagementClient wmc,
			String senderPubKey, String remotePeerPubKey, String playpenDirWithError) {
		workForPeer(component, wmc, senderPubKey, remotePeerPubKey, true, true, false,
				true, false, true, false, playpenDirWithError, null);
	}
	
	public void workForPeerOnAllocatedForMyGridWorkerWithCleaningErrorAndFileOnTransfer(WorkerComponent component,
			WorkerManagementClient wmc,	String senderPubKey, String remotePeerPubKey,
				String playpenDirWithError, List<TransferHandle> handles) {
		workForPeer(component, wmc, senderPubKey, remotePeerPubKey, true, true, false,
				true, false, true, true, playpenDirWithError, handles);
	}
	
	public void workForPeerOnAllocatedForMyGridWorkerWithFileOnTranfer(WorkerComponent component,
			WorkerManagementClient wmc,	String senderPubKey, String remotePeerPubKey,
				boolean isIncomingFile, List<TransferHandle> handles) {
		workForPeer(component, wmc, senderPubKey, remotePeerPubKey, true, true, false,
				true, false, true, false, null, handles);
	}
	
	public void workForPeerOnAllocatedForPeerWorker(WorkerComponent component, WorkerManagementClient wmc,
			String senderPubKey, String remotePeerPubKey) {
		workForPeer(component, wmc, senderPubKey, remotePeerPubKey, true, true, false,
				false, false, true, false, null, null);
	}

	private void workForPeer(WorkerComponent component, WorkerManagementClient wmc, String senderPubKey,
			String remotePeerPubKey, boolean isPeerKnown, boolean isPeerMaster, boolean isWorkerOwner,
			boolean isWorkerAllocatedForMyGrid, boolean isWorkerIdle, boolean cleans, boolean isIncomingFile,
			String playpenDirWithError, List<TransferHandle> handles) {
		
		CommuneLogger oldLogger = component.getLogger();
		CommuneLogger newLogger = EasyMock.createMock(CommuneLogger.class);
		
		component.setLogger(newLogger);
		
		WorkerManagement workerManag = getWorkerManagement();
		ObjectDeployment wmOD = getWorkerManagementDeployment();
		
		if(wmc != null) {
			EasyMock.reset(wmc);
			wmc.statusChangedAllocatedForPeer(EasyMock.isA(RemoteWorkerManagement.class));
			EasyMock.replay(wmc);
		}
		
		FileTransferManager ftm = EasyMock.createMock(FileTransferManager.class);
		component.setFileTransferManager(ftm);
		
		if(!isPeerKnown) {
			newLogger.warn("An unknown peer tried to command this Worker to work for a remote peer. " +
					"This message was ignored. Unknown peer public key: [" + senderPubKey + "].");
		} else {
			if(!isPeerMaster) {
				newLogger.debug("The master Peer tried to manage this Worker before setting itself as manager " +
				"of this Worker. This message was ignored.");
			} else {
				if(isWorkerOwner) {
					newLogger.debug("This Worker was commanded to work for a remote peer, " +
							"but it is in the OWNER status. This message was ignored.");
				} else {
					newLogger.info("Peer commanded this Worker to work for a remote peer. " +
							"Remote peer public key: [" + remotePeerPubKey + "].");

					if(isWorkerAllocatedForMyGrid) {
						newLogger.warn("Strange behavior: This Worker was allocated to a local consumer, " +
								"but was now commanded to work for a remote peer.");
						newLogger.debug("Status changed from ALLOCATED_FOR_BROKER to ALLOCATED_FOR_PEER.");
					} else {
						if(isWorkerIdle) {
							newLogger.debug("Status changed from IDLE to ALLOCATED_FOR_PEER.");
						}
					}
					if(cleans) {
						newLogger.debug("Cleaning Worker.");

						if(playpenDirWithError != null) {
							newLogger.error("Error while trying to clean the playpen directory [" + playpenDirWithError + "].");
						}
						
						if(handles != null) {
							if(isIncomingFile) {
								for (TransferHandle handle : handles) {
									ftm.cancelIncomingTransfer((IncomingTransferHandle) handle);
								}
							} else {
								for (TransferHandle handle : handles) {
									ftm.cancelOutgoingTransfer((OutgoingTransferHandle)handle);
								}
							}
							EasyMock.replay(ftm);
						}
					}
				}
			}
		}
		
		EasyMock.replay(newLogger);
		
		DeploymentID peerID = new DeploymentID(new ContainerID("peerUser", "peerServer", "peer", senderPubKey), "broker");
		
		AcceptanceTestUtil.setExecutionContext(component, wmOD, peerID);
		
		if (isWorkerOwner) {
			workerManag.workForPeer(senderPubKey);
		} else {
			workerManag.workForPeer(remotePeerPubKey);
		}
		
		EasyMock.verify(newLogger);
		
		if(wmc != null) {
			EasyMock.verify(wmc);
			EasyMock.reset(wmc);
//			EasyMock.replay(wmc);
		}
		
		if (handles != null) {
			EasyMock.verify(ftm);
			EasyMock.reset(ftm);
		}
		
		component.setLogger(oldLogger);
	}

}